package bb.lanxing.activity.routebook;

import static bb.lanxing.model.database.RouteBook.TYPE_BAIDU;
import static bb.lanxing.model.lushu.WayPoint.STATUS_NONE;
import static bb.lanxing.model.lushu.WayPoint.STATUS_SEARCHED;
import static bb.lanxing.model.lushu.WayPoint.STATUS_SEARCHING;
import static bb.lanxing.model.lushu.WayPoint.TYPE_CHECK_POINT;
import static bb.lanxing.model.lushu.WayPoint.TYPE_END;
import static bb.lanxing.model.lushu.WayPoint.TYPE_START;

import androidx.annotation.NonNull;
import java.util.List;

import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.model.LatLng;
import com.github.mikephil.charting.utils.Utils;
import com.umeng.socialize.net.dplus.CommonNetImpl;
import com.umeng.socialize.net.utils.SocializeProtocolConstants;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.res.ResourcesCompat;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.FragmentActivity;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.sport.SportActivity;
import bb.lanxing.adapter.WayPointSearchAdapter;
import bb.lanxing.ali.behavior.AppBehavior;
import bb.lanxing.common.anim.MapTopBarAnim;
import bb.lanxing.common.anim.MapbottomBarAnim;
import bb.lanxing.common.config.Constants;
import bb.lanxing.fragment.BaiduMapFragment;
import bb.lanxing.fragment.base.BaseMapFragment;
import bb.lanxing.lib.kt.model.geo.IGeoPoint;
import bb.lanxing.manager.BaiduLocationManager;
import bb.lanxing.manager.SharedManager;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.RouteBookPoint;
import bb.lanxing.model.database.Waypoint;
import bb.lanxing.model.lushu.WayPoint;
import bb.lanxing.model.lushu.WayPointBuilder;
import bb.lanxing.mvp.presetner.CreateRouteBookPresenterImpl;
import bb.lanxing.mvp.presetner.i.CreateRouteBookPresenter;
import bb.lanxing.mvp.view.i.CreateRouteBookView;
import bb.lanxing.util.BiCiCoorConverter;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.DensityUtil;
import bb.lanxing.util.Log;
import bb.lanxing.util.MapUtil;
import bb.lanxing.util.RouteBookUtil;
import bb.lanxing.util.RxPermissionUtil;
import bb.lanxing.util.map.MapConfigs;
import bb.lanxing.util.map.MapDrawSupport;
import bb.lanxing.util.map.MapTileChooseUtils;
import bb.lanxing.util.map.MapViewUtil;
import bb.lanxing.util.ui.BaseUIHandler;
import bb.lanxing.util.ui.InputHelper;
import bb.lanxing.view.BiciAlertDialogBuilder;

public class BaiduRouteBookCreateActivity extends BaseActivity implements View.OnClickListener, MapDrawSupport, CreateRouteBookView {
	public static final int LAUNCH_MODE_CREATE = 0;
	public static final int LAUNCH_MODE_EDIT = 1;
	private static final int MSG_REFRESH_UI = 2;
	private static final String TAG = BaiduRouteBookCreateActivity.class.getSimpleName();
	private final CreateRouteBookPresenter createRouteBookPresenter = new CreateRouteBookPresenterImpl(TYPE_BAIDU, this);
	private final Handler handler = new UIHandler(this);
	Toolbar mToolbar;
	BaseMapFragment mapFragment;
	private TextView addView;
	private ImageButton altitudeBtn;
	private ImageView centerLocationIcon;
	private LinearLayout container;
	private RelativeLayout contentView;
	private double disSum;
	private ImageButton distanceBtn;
	private TextView endView;
	private ImageView fullScreenIcon;
	private BaseMapFragment.InitListener initListener;
	private boolean isFullScreen;
	private LatLng lastDisPoint;
	private int launchMode;
	private RouteBook routeBook;
	private ScrollView mMapInfoPanel;
	private ImageButton mapChangeBtn;
	private MapTileChooseUtils mapTileChooser;
	private Button previewBtn;
	private ImageView searchBtn;
	private EditText searchText;
	private TextView startView;
	private TextView totalDistanceView;
	private ImageButton zoomIn;
	private ImageButton zoomOut;
	private LinearLayout zoomView;
	private boolean isMapReady = false;
	private boolean altitudeOpen = false;
	private boolean distanceOpen = false;
	private boolean isBuilding = false;

	private boolean isFirst = true;

	@Override public FragmentActivity getActivity() {
		return this;
	}

	@Override public Object getAltitudeMarker() {
		return null;
	}

	@Override public void setAltitudeMarker(Object altitudeMarker) {
	}

	@Override public void switchMapLocationMode(int mode) {
	}

	private void bindView(View bindSource) {
		searchText = bindSource.findViewById(R.id.searchText);
		startView = bindSource.findViewById(R.id.startView);
		endView = bindSource.findViewById(R.id.endView);
		addView = bindSource.findViewById(R.id.addView);
		container = bindSource.findViewById(R.id.container);
		centerLocationIcon = bindSource.findViewById(R.id.centerLocationIcon);
		mapChangeBtn = bindSource.findViewById(R.id.mapChangeBtn);
		altitudeBtn = bindSource.findViewById(R.id.altitudeBtn);
		distanceBtn = bindSource.findViewById(R.id.distanceBtn);
		zoomView = bindSource.findViewById(R.id.zoomView);
		zoomIn = bindSource.findViewById(R.id.zoomIn);
		zoomOut = bindSource.findViewById(R.id.zoomOut);
		fullScreenIcon = bindSource.findViewById(R.id.fullScreenIcon);
		searchBtn = bindSource.findViewById(R.id.searchBtn);
		previewBtn = bindSource.findViewById(R.id.previewBtn);
		mMapInfoPanel = bindSource.findViewById(R.id.mMapInfoPanel);
		totalDistanceView = bindSource.findViewById(R.id.totalDistanceView);
		contentView = bindSource.findViewById(R.id.content_view);
	}

	@Override public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lushu_create_multi_map);
		bindView(getWindow().getDecorView());
		mToolbar = setupActionBar(true);
		startView.setOnClickListener(this);
		endView.setOnClickListener(this);
		addView.setOnClickListener(this);
		mapChangeBtn.setOnClickListener(this);
		altitudeBtn.setOnClickListener(this);
		distanceBtn.setOnClickListener(this);
		zoomIn.setOnClickListener(this);
		zoomOut.setOnClickListener(this);
		fullScreenIcon.setOnClickListener(this);
		searchBtn.setOnClickListener(this);
		previewBtn.setOnClickListener(this);
		searchText.setOnEditorActionListener((v, actionId, event) -> {
			if (actionId == EditorInfo.IME_ACTION_SEARCH) {
				searchPoi();
				return true;
			}
			return false;
		});
		launchMode = getIntent().getIntExtra("launch_mode", LAUNCH_MODE_CREATE);
		long longExtra = getIntent().getLongExtra(SportActivity.EXTRA_LUSHU_ID, -1L);
		if (longExtra > 0) {
			routeBook = RouteBook.getById(longExtra);
		}
		int i = launchMode;
		if (i == LAUNCH_MODE_EDIT && routeBook == null) {
			finish();
			App.getContext().showMessage(R.string.lushu_toast_no_lushu);
			return;
		}
		setTitle(i == LAUNCH_MODE_CREATE ? R.string.lushu_create_title_create : R.string.lushu_create_title_edit);
	}

	// 再次加载的时候需要判断空
	private void initMap() {
		if (null == mapFragment) {
			initData();
			if (launchMode == LAUNCH_MODE_CREATE) {
				selectItem(0);
			} else {
				previewRouteBook();
			}
			IGeoPoint earth = createRouteBookPresenter.getStartWayPoint().toEarth(true);
			LatLng earth2Baidu = BiCiCoorConverter.earth2Baidu(new LatLng(earth.getLatitude(), earth.getLongitude()));
			final int i = SharedManager.getInstance().getInt(MapConfigs.MULTI_MAP_TILE, 0);
			Log.e("lastLoc", "lat == " + earth2Baidu.latitude + "lon == " + earth2Baidu.longitude);
			if (earth2Baidu.longitude == Utils.DOUBLE_EPSILON && earth2Baidu.latitude == Utils.DOUBLE_EPSILON) {
				new BaiduLocationManager.LocationChangedListener() {
					@Override public void onLocationChanged(LatLng earthLatlng) {
						LatLng earth2Baidu2 = BiCiCoorConverter.earth2Baidu(earthLatlng);
						mapFragment = BaiduMapFragment.newInstance(earth2Baidu2.latitude, earth2Baidu2.longitude, false, 16.0f, 1, i);
					}
				};
				BaiduLocationManager.getInstance().fetchLocationOnce();
			} else {
				mapFragment = BaiduMapFragment.newInstance(earth2Baidu.latitude, earth2Baidu.longitude, false, 16.0f, 1, i);
			}
			mapTileChooser = new MapTileChooseUtils(mapChangeBtn, contentView, mapFragment, i, new MapTileChooseUtils.MapTileChangedListener() {
				@Override public void workoutMapIdChangge(long workoutId, int mapId) {
				}

				@Override public boolean beforeChange() {
					if (isMapReady) {
						resetMapData();
					}
					return isMapReady;
				}

				@Override public void afterChanged(BaseMapFragment newMapFragment, int newType) {
					if (newMapFragment == null || newMapFragment.equals(mapFragment)) {
						return;
					}
					mapFragment = newMapFragment;
					initMapListener();
					isMapReady = false;
					getSupportFragmentManager().beginTransaction().replace(R.id.map_container, mapFragment).commit();
				}
			});
			Log.i(TAG, "onCreate: " + earth2Baidu);
			initListener = fragment -> {
				isMapReady = true;
				if (!zoomIn.isEnabled() && mapFragment.getZoomLevel() < mapFragment.getMaxOrMinZoom(true)) {
					zoomIn.setEnabled(true);
				}
				if (!zoomOut.isEnabled() && mapFragment.getZoomLevel() > mapFragment.getMaxOrMinZoom(false)) {
					zoomOut.setEnabled(true);
				}
				drawPoint();
				refreshUI();
			};
			initMapListener();
			if (mapFragment != null) {
				getSupportFragmentManager().beginTransaction().replace(R.id.map_container, mapFragment).commit();
			} else {
				mapFragment = BaiduMapFragment.newInstance(earth2Baidu.latitude, earth2Baidu.longitude, false, 16.0f, 1, i);
				getSupportFragmentManager().beginTransaction().replace(R.id.map_container, mapFragment).commit();
			}
			mapFragment.setLocationChangedListener(this::update);
		}
	}

	@Override public void onResume() {
		super.onResume();
		checkLocationPermission();
	}

	private void checkLocationPermission() {
		if (RxPermissionUtil.getInstance().checkPermission(this, RxPermissionUtil.getLocationStoragePermission())) {
			initMap();
		} else {
			showLocationPermissionDialog();
		}
	}

	private void showLocationPermissionDialog() {
		new BiciAlertDialogBuilder(this).setTitle(getString(R.string.permission_request_permission_tips)).setMessage(getResources().getString(R.string.permission_lushu_need_storage_and_loc)).setCancelable(true).setPositiveButton(R.string.dialog_btn_ok, (dialogInterface, i) -> requestLocationPermission()).setNegativeButton(R.string.skip, (dialog, which) -> {
		}).create().show();
	}

	public void requestLocationPermission() {
		RxPermissionUtil.getInstance().setPermissions(RxPermissionUtil.getLocationStoragePermission()).permissionRequestEachCombined(this, new RxPermissionUtil.PermissionCallBack() {
			@Override public void granted() {
				if (!App.isManagersInit) {
					App.getContext().initManagersWithPermissions();
				}
				initMap();
			}

			@Override public void deny() {
				App.getContext().showMessage(R.string.sport_all_permission_title);
			}
		});
	}

	private void initData() {
		if (routeBook != null) {
			List<Waypoint> byLushuId = Waypoint.getByLushuId(routeBook.getId());
			if (byLushuId != null && !byLushuId.isEmpty()) {
				for (int i = 0; i < byLushuId.size(); i++) {
					Waypoint waypoint = byLushuId.get(i);
					if (i == 0) {
						WayPoint start = createRouteBookPresenter.newWayPointBuilder().wayPointType(TYPE_START).lat(waypoint.getLatitude()).lng(waypoint.getLongitude()).type(0).address(waypoint.getContent()).title(waypoint.getTitle()).status(STATUS_NONE).build();
						createRouteBookPresenter.setTagForWayPoint(start, makeMarker(start));
						createRouteBookPresenter.addWayPoints(start);
					} else if (i == byLushuId.size() - 1) {
						WayPoint end = createRouteBookPresenter.newWayPointBuilder().lat(waypoint.getLatitude()).lng(waypoint.getLongitude()).wayPointType(TYPE_END).address(waypoint.getContent()).title(waypoint.getTitle()).type(0).status(STATUS_NONE).build();
						createRouteBookPresenter.setTagForWayPoint(end, makeMarker(end));
						createRouteBookPresenter.addWayPoints(end);
					} else {
						WayPoint middle = createRouteBookPresenter.newWayPointBuilder().lat(waypoint.getLatitude()).lng(waypoint.getLongitude()).wayPointType(TYPE_CHECK_POINT).type(0).address(waypoint.getContent()).title(waypoint.getTitle()).build();
						addItemMarkerAndView(i, middle);
						createRouteBookPresenter.addWayPoints(middle);
					}
				}
			} else {
				List<RouteBookPoint> routeBookPointList = RouteBookPoint.getByLushuId(routeBook.getId());
				if (routeBookPointList != null && !routeBookPointList.isEmpty()) {
					WayPoint start = createRouteBookPresenter.newWayPointBuilder().wayPointType(TYPE_START).lat(routeBookPointList.get(0).getLatLng().latitude).lng(routeBookPointList.get(0).getLatLng().longitude).type(0).status(STATUS_NONE).build();
					createRouteBookPresenter.setTagForWayPoint(start, makeMarker(start));
					createRouteBookPresenter.addWayPoints(start);
					WayPoint end = createRouteBookPresenter.newWayPointBuilder().lat(routeBookPointList.get(routeBookPointList.size() - 1).getLatLng().latitude).lng(routeBookPointList.get(routeBookPointList.size() - 1).getLatLng().longitude).wayPointType(TYPE_END).type(0).status(STATUS_NONE).build();
					createRouteBookPresenter.setTagForWayPoint(end, makeMarker(end));
					createRouteBookPresenter.addWayPoints(end);
				}
			}
			previewRouteBook();
		}
		if (createRouteBookPresenter.getWayPointSize() < 2) {
			LatLng pLatLng = MapConfigs.getNotNullLastLocation();
			update(pLatLng);
		}
	}

	public void initMapListener() {
		BaseMapFragment baseMapFragment = mapFragment;
		if (baseMapFragment == null) {
			return;
		}
		baseMapFragment.setInitListener(initListener);
		mapFragment.setMapViewListener(new BaseMapFragment.MapViewListener<Object, LatLng, Object, Object>() {
			boolean start = false;

			@Override public void onMakerClick(Object marker) {
			}

			@Override public void onMapLongClick(Object mapView, LatLng point) {
			}

			@Override public void onPolylineClick(Object polyline) {
			}

			@Override public void onDragMap(Object mapView, boolean end) {
				WayPoint selectedWayPoint = createRouteBookPresenter.getSelectedWayPoint();
				if (selectedWayPoint == null) {
					return;
				}
				if (end) {
					start = false;
					if (selectedWayPoint.getStatus() == STATUS_NONE) {
						return;
					}
					LatLng center = mapFragment.getCenter();
					if (mapFragment instanceof BaiduMapFragment) {
						center = BiCiCoorConverter.baidu2Earth(center);
					}
					updateCurrentWayPointInfo(selectedWayPoint.newBuilder().lat(center.latitude).lng(center.longitude).type(0).build());
				} else {
					if (!start) {
						start = true;
						if (selectedWayPoint.getStatus() == STATUS_NONE || selectedWayPoint.getStatus() == STATUS_SEARCHING) {
							return;
						}
						createRouteBookPresenter.setStatusForWayPoint(selectedWayPoint, STATUS_SEARCHING);
					}
				}
			}

			@Override public void onMapClick(Object mapView, LatLng point) {
				LatLng common2Earth;
				if (mapFragment instanceof BaiduMapFragment) {
					common2Earth = BiCiCoorConverter.baidu2Earth(point);
				} else {
					// TODO:fdl
					// common2Earth = mapFragment instanceof OsmMapFragment ? BiCiCoorConverter.common2Earth(point) :
					// point;
					common2Earth = point;
				}
				if (!distanceOpen) {
					if (altitudeOpen) {
						MapViewUtil.drawAltitude(BaiduRouteBookCreateActivity.this, point, common2Earth, null);
						return;
					}
					return;
				}
				MapViewUtil.drawDistance(BaiduRouteBookCreateActivity.this, point, common2Earth, null);
			}

			@Override public void onZoom(float zoom) {
				if (zoomIn.isEnabled()) {
					if (zoom >= mapFragment.getMaxOrMinZoom(true)) {
						zoomIn.setEnabled(false);
					}
				} else if (zoom < mapFragment.getMaxOrMinZoom(true)) {
					zoomIn.setEnabled(true);
				}
				if (zoomOut.isEnabled()) {
					if (zoom <= mapFragment.getMaxOrMinZoom(false)) {
						zoomOut.setEnabled(false);
					}
				} else if (zoom > mapFragment.getMaxOrMinZoom(false)) {
					zoomOut.setEnabled(true);
				}
			}
		});
	}

	@Override public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_lushu_create, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override public boolean onOptionsItemSelected(@NonNull MenuItem item) {
		if (R.id.action_done == item.getItemId()) {
			buildRouteBook();
		}
		return super.onOptionsItemSelected(item);
	}

	@Override public boolean onHomeBack() {
		return !exit() || super.onHomeBack();
	}

	@Override public void onBackPressed() {
		if (exit()) {
			super.onBackPressed();
		}
	}

	@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
		int intExtra;
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Constants.REQUEST_CODE) {
			if (resultCode == Constants.RESULT_CODE_LUSHU_EDIT || resultCode == Constants.RESULT_CODE_LUSHU_DELETE) {
				setResult(RESULT_OK);
				finish();
			} else {
				if (resultCode == Constants.RESULT_CODE_LUSHU_WAYPOINT_EDIT && data != null && (intExtra = data.getIntExtra(CommonNetImpl.POSITION, -1)) != -1) {
					createRouteBookPresenter.setWayPointAt(intExtra, createRouteBookPresenter.getWayPointAt(intExtra).newBuilder().title(data.getStringExtra("title")).content(data.getStringExtra("content")).address(data.getStringExtra("content")).image(data.getStringExtra(SocializeProtocolConstants.IMAGE)).wayPointType(data.getBooleanExtra("isShow", false) ? 4 : 3).build());
					refreshMarkers();
					refreshUI();
				}
			}
		}
	}

	@Override public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.addView) {
			if (container.getChildCount() >= 23) {
				App.getContext().showMessage(R.string.lushu_create_toast_waypoint_limit_23);
				return;
			}
			centerLocationIcon.setImageResource(R.drawable.ic_lushu_edit_map_waypoint_up);
			centerLocationIcon.setPadding(0, 0, 0, DensityUtil.dp2px(40.0f));
			addItem();
		} else if (id == R.id.altitudeBtn) {
			onAltitudeClick();
		} else if (id == R.id.distanceBtn) {
			onDistanceClick();
		} else if (id == R.id.endView) {
			int wayPointSize = createRouteBookPresenter.getWayPointSize() - 1;
			WayPoint endWayPoint = createRouteBookPresenter.getEndWayPoint();
			if (endWayPoint.getTag() == null) {
				if (endWayPoint.getLatitude() == Utils.DOUBLE_EPSILON && endWayPoint.getLongitude() == Utils.DOUBLE_EPSILON) {
					WayPoint wayPointAt = createRouteBookPresenter.getWayPointAt(wayPointSize - 1);
					endWayPoint = endWayPoint.newBuilder().lat(wayPointAt.getLatitude()).lng(wayPointAt.getLongitude()).type(wayPointAt.getType()).build();
					createRouteBookPresenter.setWayPointAt(wayPointSize, endWayPoint);
				}
				createRouteBookPresenter.setTagForWayPoint(endWayPoint, makeMarker(endWayPoint));
			}
			centerLocationIcon.setImageResource(R.drawable.ic_lushu_map_endpoint_up);
			centerLocationIcon.setPadding(0, 0, 0, DensityUtil.dp2px(47.0f));
			selectItem(wayPointSize);
		} else if (id == R.id.fullScreenIcon) {
			boolean z = !isFullScreen;
			isFullScreen = z;
			switchFullScreenState(z);
		} else if (id == R.id.mapChangeBtn) {
			mapTileChooser.show();
		} else if (id == R.id.previewBtn) {
			previewRouteBook();
		} else if (id == R.id.searchBtn) {
			searchPoi();
		} else if (id == R.id.startView) {
			centerLocationIcon.setImageResource(R.drawable.ic_lushu_map_startpoint_up);
			centerLocationIcon.setPadding(0, 0, 0, DensityUtil.dp2px(47.0f));
			selectItem(0);
		} else if (id == R.id.zoomIn) {
			if (mapFragment != null) {
				Log.i(TAG, "onClick: zoom in " + mapFragment.getZoomLevel());
				mapFragment.zoomIn();
			}
		} else if (id == R.id.zoomOut) {
			if (mapFragment != null) {
				Log.i(TAG, "onClick: zoom out " + mapFragment.getZoomLevel());
				mapFragment.zoomOut();
			}
		}
	}

	public void searchPoi() {
		InputHelper.hideSoftInput(searchText);
		String obj = searchText.getText().toString();
		if (TextUtils.isEmpty(obj)) {
			App.getContext().showMessage(R.string.lushu_toast_input_search);
		} else {
			createRouteBookPresenter.search(obj);
		}
	}

	private void previewRouteBook() {
		createRouteBookPresenter.preview();
		refreshUI();
	}

	private void buildRouteBook() {
		if (isBuilding) {
			return;
		}
		isBuilding = true;
		WayPoint startWayPoint = createRouteBookPresenter.getStartWayPoint();
		if (startWayPoint.getLongitude() == Utils.DOUBLE_EPSILON && startWayPoint.getLongitude() == Utils.DOUBLE_EPSILON) {
			App.getContext().showMessage(R.string.lushu_create_toast_choose_start_point_first);
			isBuilding = false;
			return;
		}
		WayPoint endWayPoint = createRouteBookPresenter.getEndWayPoint();
		if (endWayPoint.getLongitude() == Utils.DOUBLE_EPSILON && endWayPoint.getLongitude() == Utils.DOUBLE_EPSILON) {
			App.getContext().showMessage(R.string.lushu_create_toast_choose_stop_point_first);
			isBuilding = false;
			return;
		}
		if (launchMode == LAUNCH_MODE_EDIT && routeBook != null) {
			createRouteBookPresenter.reBuild(routeBook);
		} else {
			createRouteBookPresenter.build();
		}
		AppBehavior.route().create().submit();
	}

	public void drawPoint() {
		List<WayPoint> wayPoints = createRouteBookPresenter.getWayPoints();
		if (mapFragment == null || wayPoints == null || wayPoints.isEmpty()) {
			return;
		}
		mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_NAV);
		for (WayPoint wayPoint : wayPoints) {
			if (wayPoint.getLongitude() != Utils.DOUBLE_EPSILON && wayPoint.getLatitude() != Utils.DOUBLE_EPSILON) {
				createRouteBookPresenter.setTagForWayPoint(wayPoint, makeMarker(wayPoint));
			}
		}
	}

	private void editRouteBookInfo(long routeBookId) {
		Intent intent = new Intent(this, RouteBookEditActivity.class);
		intent.putExtra(SportActivity.EXTRA_LUSHU_ID, routeBookId);
		intent.putExtra("from_create", true);
		startActivityForResult(intent, Constants.REQUEST_CODE);
	}

	private boolean exit() {
		if (isFullScreen) {
			isFullScreen = false;
			switchFullScreenState(false);
			return false;
		}
		new BiciAlertDialogBuilder(this).setMessage(R.string.lushu_create_dialog_exit_prompt).setNegativeButton(R.string.exit, (dialog, which) -> {
			if (routeBook != null) {
				RouteBookUtil.deleteRouteBook(routeBook);
			}
			finish();
		}).setPositiveButton(R.string.keep_edit, null).setTitle(R.string.dialog_prompt).show();
		return false;
	}

	public void selectItem(int index) {
		Log.v(TAG, "selectItem, index = " + index);
		createRouteBookPresenter.selectWayPoint(index);
	}

	private void addItem() {
		IGeoPoint baidu = createRouteBookPresenter.getWayPointAt(createRouteBookPresenter.getWayPointSize() - 2).toBaidu(true);
		addItem(createRouteBookPresenter.getWayPointSize() - 1, new LatLng(baidu.getLatitude(), baidu.getLongitude()));
	}

	private void addItem(int itemIndex, LatLng latLng) {
		WayPointBuilder wayPointType = createRouteBookPresenter.newWayPointBuilder().wayPointType(4);
		WayPoint build = wayPointType.title("途经点" + itemIndex).lat(latLng.latitude).lng(latLng.longitude).type(2).build();
		createRouteBookPresenter.setTagForWayPoint(build, makeMarker(build));
		createRouteBookPresenter.insertWayPointBefore(createRouteBookPresenter.getEndWayPoint(), build);
		addItemMarkerAndView(itemIndex, build);
	}

	private void addItemMarkerAndView(int itemIndex, WayPoint wayPoint) {
		LinearLayout linearLayout = (LinearLayout) View.inflate(this, R.layout.lushu_edit_waypoint_item, null);
		container.addView(linearLayout);
		linearLayout.setTag(itemIndex);
		linearLayout.setOnClickListener(view -> selectItem((Integer) view.getTag()));
		linearLayout.setOnLongClickListener(view -> {
			showOptionDialog((Integer) view.getTag());
			return true;
		});
		ImageView imageView = linearLayout.findViewById(R.id.editView);
		imageView.setTag(itemIndex);
		imageView.setOnClickListener(view -> editWaypoint((Integer) view.getTag()));
		selectItem(itemIndex);
	}

	private Object makeMarker(WayPoint displayPoint) {
		Drawable makeMarkerIcon = makeMarkerIcon(displayPoint);
		if (mapFragment == null) {
			return null;
		}
		Log.i(TAG, "makeMarker: " + displayPoint);
		return mapFragment.drawMarker(BaseMapFragment.OVERLAY_TYPE_NAV, displayPoint.toEarth(true), makeMarkerIcon, null, 0.5f, (displayPoint.getWayPointType() == 3 || displayPoint.getWayPointType() == 4) ? 0.972f : 0.95f);
	}

	public void removeMarkerForWayPoint(WayPoint point) {
		if (null != point) {
			Object tag = point.getTag();
			if (tag != null) {
				mapFragment.removeOverlay(tag, 0);
			}
		}
	}

	private void refreshMarkers() {
		for (WayPoint wayPoint : createRouteBookPresenter.getWayPoints()) {
			setMarkerIcon(wayPoint, makeMarkerIcon(wayPoint));
		}
	}

	public void clearMarkers() {
		mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_ROAD_BOOK);
		mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_ALTITUDE);
		mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_DISTANCE);
	}

	private Drawable makeMarkerIcon(WayPoint displayPoint) {
		int i;
		int i2;
		int wayPointType = displayPoint.getWayPointType();
		if (wayPointType == TYPE_START) {
			return ResourcesCompat.getDrawable(getResources(), R.drawable.ic_lushu_map_startpoint, getTheme());
		}
		if (wayPointType == TYPE_END) {
			return ResourcesCompat.getDrawable(getResources(), R.drawable.ic_lushu_map_endpoint, getTheme());
		}
		String title = displayPoint.getTitle();
		if (wayPointType == TYPE_CHECK_POINT) {
			i = R.drawable.ring_2dip_no_side_green;
			i2 = R.drawable.ic_lushu_map_checkpoint;
		} else {
			i = R.drawable.ring_2dip_no_side_blue;
			i2 = R.drawable.ic_lushu_edit_map_waypoint;
		}
		View inflate = LayoutInflater.from(this).inflate(R.layout.map_marker_with_text, null);
		((TextView) inflate.findViewById(R.id.nameView)).setText(title);
		inflate.findViewById(R.id.nameView).setBackgroundResource(i);
		((ImageView) inflate.findViewById(R.id.iconView)).setImageResource(i2);
		return MapUtil.convertView(inflate);
	}

	public void showOptionDialog(final int position) {
		new AlertDialog.Builder(this).setItems(new String[] { getString(R.string.delete) }, (dialog, which) -> {
			if (which != 0) {
				return;
			}
			container.removeViewAt(position - 1);
			refreshContainerViewsTag();
			removeMarkerForWayPoint(createRouteBookPresenter.removeAt(position));
		}).show();
	}

	public void editWaypoint(int position) {

		WayPoint wayPointAt = createRouteBookPresenter.getWayPointAt(position);
		Intent intent = new Intent(this, RouteBookWaypointEditActivity.class);
		intent.putExtra(CommonNetImpl.POSITION, position);
		intent.putExtra("title", wayPointAt.getTitle());
		intent.putExtra("content", wayPointAt.getContent());
		intent.putExtra(SocializeProtocolConstants.IMAGE, wayPointAt.getImage());
		intent.putExtra("isShow", wayPointAt.getWayPointType() == 4);
		startActivityForResult(intent, Constants.REQUEST_CODE);
	}

	public void switchFullScreenState(boolean isFullScreen) {
		fullScreenIcon.setImageResource(isFullScreen ? R.drawable.ic_fullscreen_quit : R.drawable.ic_fullscreen);
		if (isFullScreen) {
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) fullScreenIcon.getLayoutParams();
			layoutParams.setMargins(0, 0, DensityUtil.dp2px(16.0f), DensityUtil.dp2px(150.0f));
			fullScreenIcon.setLayoutParams(layoutParams);
			hideTopBar();
			hideInfoPanel();
		} else {
			showTopBar();
			showInfoPanel();
		}
		mapChangeBtn.setVisibility(isFullScreen ? View.VISIBLE : View.GONE);
		altitudeBtn.setVisibility(isFullScreen ? View.VISIBLE : View.GONE);
		distanceBtn.setVisibility(isFullScreen ? View.VISIBLE : View.GONE);
		zoomView.setVisibility(isFullScreen ? View.VISIBLE : View.GONE);
	}

	private void showTopBar() {
		MapTopBarAnim mapTopBarAnim = new MapTopBarAnim(true);
		mapTopBarAnim.onCreate(this, mToolbar.getHeight(), true);
		mapTopBarAnim.setAnimationListener(new Animation.AnimationListener() {
			@Override public void onAnimationRepeat(Animation animation) {
			}

			@Override public void onAnimationStart(Animation animation) {
			}

			@Override public void onAnimationEnd(Animation animation) {
				mToolbar.clearAnimation();
				mToolbar.setVisibility(View.VISIBLE);
			}
		});
		mToolbar.clearAnimation();
		mToolbar.setVisibility(View.VISIBLE);
		mToolbar.startAnimation(mapTopBarAnim);
	}

	public void hideTopBar() {
		MapTopBarAnim mapTopBarAnim = new MapTopBarAnim(true);
		mapTopBarAnim.onCreate(this, mToolbar.getHeight(), false);
		mapTopBarAnim.setAnimationListener(new Animation.AnimationListener() {
			@Override public void onAnimationRepeat(Animation animation) {
			}

			@Override public void onAnimationStart(Animation animation) {
			}

			@Override public void onAnimationEnd(Animation animation) {
				mToolbar.clearAnimation();
				mToolbar.setVisibility(View.GONE);
			}
		});
		mToolbar.clearAnimation();
		mToolbar.startAnimation(mapTopBarAnim);
	}

	public void showInfoPanel() {
		final LatLng center = mapFragment.getCenter();
		MapbottomBarAnim mapbottomBarAnim = new MapbottomBarAnim(true);
		mapbottomBarAnim.onCreate(this, mMapInfoPanel.getHeight(), true);
		mapbottomBarAnim.setAnimationListener(new Animation.AnimationListener() {
			@Override public void onAnimationRepeat(Animation animation) {
			}

			@Override public void onAnimationStart(Animation animation) {
			}

			@Override public void onAnimationEnd(Animation animation) {
				mMapInfoPanel.clearAnimation();
				mMapInfoPanel.setVisibility(View.VISIBLE);
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) fullScreenIcon.getLayoutParams();
				layoutParams.setMargins(0, 0, DensityUtil.dp2px(16.0f), DensityUtil.dp2px(16.0f));
				fullScreenIcon.setLayoutParams(layoutParams);
				if (center == null || mapFragment == null) {
					return;
				}
				mMapInfoPanel.post(() -> mapFragment.moveTo(center.latitude, center.longitude));
			}
		});
		mMapInfoPanel.clearAnimation();
		mMapInfoPanel.setVisibility(View.VISIBLE);
		mMapInfoPanel.startAnimation(mapbottomBarAnim);
	}

	private void hideInfoPanel() {
		final LatLng center = mapFragment.getCenter();
		MapbottomBarAnim mapbottomBarAnim = new MapbottomBarAnim(true);
		mapbottomBarAnim.onCreate(this, mMapInfoPanel.getHeight(), false);
		mapbottomBarAnim.setAnimationListener(new Animation.AnimationListener() {
			@Override public void onAnimationRepeat(Animation animation) {
			}

			@Override public void onAnimationStart(Animation animation) {
			}

			@Override public void onAnimationEnd(Animation animation) {
				mMapInfoPanel.clearAnimation();
				mMapInfoPanel.setVisibility(View.GONE);
				if (center == null || mapFragment == null) {
					return;
				}
				mMapInfoPanel.post(() -> mapFragment.moveTo(center.latitude, center.longitude));
			}
		});
		mMapInfoPanel.clearAnimation();
		mMapInfoPanel.startAnimation(mapbottomBarAnim);
	}

	public void refreshUI() {
		refreshItemsUI();
		refreshMapUI();
	}

	private void refreshItemsUI() {
		runOnUiThread(() -> {
			int color;
			List<WayPoint> wayPoints = createRouteBookPresenter.getWayPoints();
			int index;
			for (index = 0; index < wayPoints.size(); ++index) {
				WayPoint wayPoint = wayPoints.get(index);
				String address = wayPoint.getAddress();
				if (wayPoint.getStatus() == STATUS_SEARCHING || (TextUtils.isEmpty(address))) {
					color = getResources().getColor(R.color.md_grey_500);
				} else if (wayPoint.getStatus() == STATUS_NONE) {
					color = getResources().getColor(R.color.black);
				} else {
					color = getResources().getColor(R.color.global_blue_second_color);
				}
				if (wayPoint.getWayPointType() == TYPE_START) {
					if (TextUtils.isEmpty(address)) {
						address = getString(R.string.lushu_create_hint_choose_start_point);
					}
					startView.setText(address);
					startView.setTextColor(color);
				} else if (wayPoint.getWayPointType() == TYPE_END) {
					if (TextUtils.isEmpty(address)) {
						address = getString(R.string.lushu_create_hint_choose_stop_point);
					}
					endView.setText(address);
					endView.setTextColor(color);
				} else {
					int v6 = (wayPoints.get(index)).getWayPointType() == TYPE_CHECK_POINT ? R.drawable.ic_lushu_checkpoint : R.drawable.ic_lushu_item_waypoint;
					if (TextUtils.isEmpty(address)) {
						address = getString(R.string.lushu_create_hint_choose_waypoint);
					}
					int middle = index - 1;
					if (middle >= 0 && middle < container.getChildCount()) {
						LinearLayout middleContainer = (LinearLayout) container.getChildAt(middle);
						ImageView v9 = middleContainer.findViewById(R.id.waypointIcon);
						TextView v10 = middleContainer.findViewById(R.id.waypointView);
						TextView v8_2 = middleContainer.findViewById(R.id.checkpointView);
						v9.setImageResource(v6);
						v10.setText(address);
						v10.setTextColor(color);
						v8_2.setText((wayPoint.getWayPointType() == TYPE_CHECK_POINT ? wayPoint.getTitle() : ""));
						v8_2.setVisibility((wayPoint.getWayPointType() == TYPE_CHECK_POINT ? View.VISIBLE : View.GONE));
					}
				}
			}
		});
	}

	private void refreshMapUI() {
		runOnUiThread(() -> {
			WayPoint selectedWayPoint = createRouteBookPresenter.getSelectedWayPoint();
			if (selectedWayPoint == null) {
				return;
			}
			int type = selectedWayPoint.getWayPointType();
			Log.i("refreshMapUI selectedWayPoint type = " + type + ",address = " + selectedWayPoint.getAddress());
			setMarkerVisible(selectedWayPoint, selectedWayPoint.getStatus() == STATUS_NONE);
			List<WayPoint> wayPoints = createRouteBookPresenter.getWayPoints();
			for (int i = 0; i < wayPoints.size(); i++) {
				if (i != createRouteBookPresenter.getSelectedIndex()) {
					setMarkerVisible(wayPoints.get(i), true);
				}
			}
			if (type == TYPE_START) {
				centerLocationIcon.setImageResource(selectedWayPoint.getStatus() == STATUS_SEARCHED ? R.drawable.ic_lushu_map_startpoint : R.drawable.ic_lushu_map_startpoint_up);
				centerLocationIcon.setPadding(0, 0, 0, selectedWayPoint.getStatus() == STATUS_SEARCHED ? DensityUtil.dp2px(35.0f) : DensityUtil.dp2px(47.0f));
			} else if (type == TYPE_END) {
				centerLocationIcon.setImageResource(selectedWayPoint.getStatus() == STATUS_SEARCHED ? R.drawable.ic_lushu_map_endpoint : R.drawable.ic_lushu_map_endpoint_up);
				centerLocationIcon.setPadding(0, 0, 0, selectedWayPoint.getStatus() == STATUS_SEARCHED ? DensityUtil.dp2px(35.0f) : DensityUtil.dp2px(47.0f));
			} else {
				centerLocationIcon.setImageResource(createRouteBookPresenter.getSelectedWayPoint().getWayPointType() == TYPE_CHECK_POINT ? selectedWayPoint.getStatus() == STATUS_SEARCHED ? R.drawable.ic_lushu_map_checkpoint : R.drawable.ic_lushu_map_checkpoint_up : selectedWayPoint.getStatus() == 3 ? R.drawable.ic_lushu_edit_map_waypoint : R.drawable.ic_lushu_edit_map_waypoint_up);
				centerLocationIcon.setPadding(0, 0, 0, DensityUtil.dp2px(selectedWayPoint.getStatus() == STATUS_SEARCHED ? 28.0f : 40.0f));
			}
			centerLocationIcon.setVisibility(selectedWayPoint.getStatus() == STATUS_NONE ? View.GONE : View.VISIBLE);
		});
	}

	public void refreshContainerViewsTag() {
		int i = 0;
		while (i < container.getChildCount()) {
			View childAt = container.getChildAt(i);
			i++;
			childAt.setTag(i);
			ImageView imageView = childAt.findViewById(R.id.editView);
			if (imageView != null) {
				imageView.setTag(i);
			}
		}
	}

	void onAltitudeClick() {
		if (altitudeOpen) {
			altitudeBtn.setImageResource(R.drawable.ic_map_altitude_off);
			if (mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_ALTITUDE)) {
				App.getContext().showMessage(R.string.map_clear_altitude_info);
			}
			altitudeOpen = false;
			return;
		}
		if (distanceOpen) {
			distanceBtn.setImageResource(R.drawable.ic_map_length_off);
			if (mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_DISTANCE)) {
				lastDisPoint = null;
			}
			distanceOpen = false;
		}
		altitudeBtn.setImageResource(R.drawable.ic_map_altitude_on);
		App.getContext().showMessage(R.string.map_click_show_altitude);
		altitudeOpen = true;
	}

	void onDistanceClick() {
		if (distanceOpen) {
			distanceBtn.setImageResource(R.drawable.ic_map_length_off);
			if (mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_DISTANCE)) {
				App.getContext().showMessage(R.string.map_clear_distance_info);
				lastDisPoint = null;
			}
			distanceOpen = false;
			return;
		}
		if (altitudeOpen) {
			altitudeBtn.setImageResource(R.drawable.ic_map_altitude_off);
			mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_ALTITUDE);
			altitudeOpen = false;
		}
		distanceBtn.setImageResource(R.drawable.ic_map_length_on);
		App.getContext().showMessage(R.string.map_click_measure_distance);
		distanceOpen = true;
	}

	@Override public void resetMapData() {
		mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_NAV);
		disSum = Utils.DOUBLE_EPSILON;
		lastDisPoint = null;
	}

	private void setMarkerVisible(WayPoint wayPoint, boolean visible) {
		Object tag = wayPoint.getTag();
		if (tag == null) {
			return;
		}
		if (tag instanceof Marker marker) {
			try {
				marker.setVisible(visible);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void setMarkerIcon(WayPoint wayPoint, Drawable icon) {
		Object tag = wayPoint.getTag();
		if (tag == null) {
			return;
		}
		if (tag instanceof Marker marker) {
			try {
				marker.setIcon(BitmapDescriptorFactory.fromBitmap(((BitmapDrawable) icon).getBitmap()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// else if (tag instanceof org.osmdroid.views.overlay.Marker) {
		// ((org.osmdroid.views.overlay.Marker) tag).setIcon(icon);
		// ((OsmMapFragment) mapFragment).invalidate();
		// }
	}

	private void showLocationSearchResultDialog(final List<WayPoint> result) {
		TextView textView = new TextView(this);
		textView.setBackgroundColor(ViewCompat.MEASURED_STATE_MASK);
		textView.setText(R.string.lushu_create_dialog_title_search);
		textView.setTextColor(-1);
		textView.setTextSize(0, getResources().getDimensionPixelOffset(R.dimen.custom_dialog_title_text_size));
		textView.setHeight(getResources().getDimensionPixelOffset(R.dimen.custom_dialog_title_bar_height));
		textView.setGravity(Gravity.CENTER);
		new BiciAlertDialogBuilder(this).setCustomTitle(textView).setCancelable(true).setSingleChoiceItems(new WayPointSearchAdapter(this, result), -1, new DialogInterface.OnClickListener() {
			@Override public void onClick(DialogInterface dialog, int which) {
				final LatLng latLng;
				WayPoint selectedWayPoint = createRouteBookPresenter.getSelectedWayPoint();
				if (selectedWayPoint.getStatus() != STATUS_SEARCHING) {
					createRouteBookPresenter.setStatusForWayPoint(selectedWayPoint, STATUS_SEARCHING);
				}
				WayPoint wayPoint = result.get(which);
				// if (mapFragment instanceof OsmMapFragment) {
				// IGeoPoint common = wayPoint.toCommon(true);
				// latLng = new LatLng(common.getLatitude(), common.getLongitude());
				// } else
				{
					IGeoPoint baidu = wayPoint.toBaidu(true);
					latLng = new LatLng(baidu.getLatitude(), baidu.getLongitude());
				}
				handler.post(() -> mapFragment.moveTo(latLng.latitude, latLng.longitude));
				updateCurrentWayPointInfo(wayPoint);
				dialog.dismiss();
			}
		}).show();
	}

	private void updateCurrentWayPointInfo(WayPoint wayPoint) {
		Log.i("updateCurrentWayPointInfo");
		WayPoint selectedWayPoint = createRouteBookPresenter.getSelectedWayPoint();
		IGeoPoint earth = wayPoint.toEarth(true);
		WayPoint build = selectedWayPoint.newBuilder().address(wayPoint.getAddress()).lat(earth.getLatitude()).lng(earth.getLongitude()).type(0).build();
		Object tag = build.getTag();
		if (tag instanceof Marker) {
			try {
				IGeoPoint baidu = build.toBaidu(true);
				((Marker) tag).setPosition(new LatLng(baidu.getLatitude(), baidu.getLongitude()));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		createRouteBookPresenter.setWayPointAt(createRouteBookPresenter.getSelectedIndex(), build);
		createRouteBookPresenter.reverseCodeForWayPoint(build);
	}

	@Override public void onDestroy() {
		clearMarkers();
		if (createRouteBookPresenter != null) {
			createRouteBookPresenter.destroy();
		}
		if (handler != null) {
			handler.removeCallbacksAndMessages(null);
		}
		super.onDestroy();
	}

	@Override public BaseMapFragment getMapFragment() {
		return mapFragment;
	}

	@Override public boolean isAltitudeOpen() {
		return altitudeOpen;
	}

	@Override public LatLng getLastDistancePoint() {
		return lastDisPoint;
	}

	@Override public void setLastDistancePoint(LatLng lastDistancePoint) {
		lastDisPoint = lastDistancePoint;
	}

	@Override public double getDistanceSum() {
		return disSum;
	}

	@Override public void setDistanceSum(double distanceSum) {
		disSum = distanceSum;
	}

	@Override public void onSelectPoint(WayPoint current) {
		if (mapFragment != null && current != null) {
			IGeoPoint iGeoPoint = null;
			if (mapFragment instanceof BaiduMapFragment) {
				iGeoPoint = current.toBaidu(true);
			}
			if (iGeoPoint != null) {
				mapFragment.moveTo(iGeoPoint.getLatitude(), iGeoPoint.getLongitude());
			}
		}
		refreshMapUI();
	}

	@Override public void onDraw(List<IGeoPoint> geoPoints, boolean inBound) {
		Log.i("RouteBookBaiduCreateActivity onDraw inBound = " + inBound);
		BaseMapFragment baseMapFragment = mapFragment;
		if (baseMapFragment != null && geoPoints != null) {
			baseMapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_ROAD_BOOK);
			if (isFirst) {
				mapFragment.clearOverlay(BaseMapFragment.OVERLAY_TYPE_NAV);
				isFirst = false;
			}
			if (!geoPoints.isEmpty()) {
				Log.i("RouteBookBaiduCreateActivity onDraw geoPoints inBound = " + inBound + ",geoPoints size = " + geoPoints.size());
				mapFragment.drawLine(BaseMapFragment.OVERLAY_TYPE_ROAD_BOOK, geoPoints, Constants.LUSHU_LINE_COLOR, inBound);
			} else {
				Log.i("RouteBookBaiduCreateActivity onDraw geoPoints isEmpty");
			}
		}
		totalDistanceView.setText(String.format("%s km", CommonUtil.getFormatDistance(createRouteBookPresenter.getDistance())));
		totalDistanceView.setVisibility(View.VISIBLE);
	}

	@Override public void onRouteBook(RouteBook routeBook) {
		totalDistanceView.setText(String.format("%s km", CommonUtil.getFormatDistance(createRouteBookPresenter.getDistance())));
		totalDistanceView.setVisibility(View.VISIBLE);
		toast(R.string.lushu_create_toast_create_successful);
		routeBook.setIsUpload(false);
		this.routeBook = routeBook;
		routeBook.save();
		if (launchMode == LAUNCH_MODE_CREATE) {
			editRouteBookInfo(routeBook.getId());
		} else {
			setResult(Activity.RESULT_OK);
			finish();
		}
		isBuilding = false;
	}

	@Override public void onSearchResult(List<WayPoint> result) {
		showLocationSearchResultDialog(result);
	}

	@Override public void onRefreshView() {
		refreshUI();
	}

	private static class UIHandler extends BaseUIHandler<BaiduRouteBookCreateActivity> {
		private UIHandler(BaiduRouteBookCreateActivity uiObj) {
			super(uiObj);
		}

		@Override public void handleMessage(Message msg, BaiduRouteBookCreateActivity uiObj) {
			if (msg.what != MSG_REFRESH_UI) {
				return;
			}
			uiObj.refreshUI();
		}
	}

	private void update(LatLng pLatLng) {
		Log.i("RouteBookBaiduCreateActivity update");
		if (createRouteBookPresenter.getDistance() > 0) {
			return;
		}
		createRouteBookPresenter.removeAllWayPoint();
		WayPoint start = createRouteBookPresenter.newWayPointBuilder().wayPointType(TYPE_START).lat(pLatLng.latitude).lng(pLatLng.longitude).type(0).status(STATUS_NONE).build();
		createRouteBookPresenter.setTagForWayPoint(start, makeMarker(start));
		createRouteBookPresenter.addWayPoints(start);
		createRouteBookPresenter.reverseCodeForWayPoint(start);
		WayPoint end = createRouteBookPresenter.newWayPointBuilder().wayPointType(TYPE_END).lat(pLatLng.latitude).lng(pLatLng.longitude).type(0).status(STATUS_NONE).build();
		createRouteBookPresenter.addWayPoints(end);
		createRouteBookPresenter.reverseCodeForWayPoint(end);
	}
}
